﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smart.Model;
using Smart.Data.Membership;
using Smart.Business.Utils;
using Smart.Data;

namespace Smart.Business.Membership
{
    /// <summary>
    /// Implement business logic for User entity
    /// </summary>
    public class UserBL
    {
        private UserDL dal = null;

        public UserBL()
        {
            if (dal == null)
            {
                dal = new UserDL(null);
            }
        }

        public UserBL(ISmartEntities context)
        {
            if (dal == null)
            {
                dal = new UserDL(context);
            }
        }

        /// <summary>
        /// Method to get all users
        /// </summary>
        public List<User> GetUsers()
        {
            return dal.GetUsers();
        }

        /// <summary>
        /// Method to validate user on login
        /// </summary>
        public bool ValidateUser(string email, string password)
        {
            User foundUser = dal.GetUserByEmail(email);

            // Check for existing user
            if (foundUser != null)
            {
                // Compare passwords with MD5 encryption
                return EncryptionUtils.Compare(password, foundUser.Password);
            }
            
            // There is no such user
            return false;
        }

        /// <summary>
        /// Method to update User object
        /// </summary>
        public User UpdateUser(User user)
        {
            return dal.SetUser(user);
        }

        /// <summary>
        /// Method to create User object and encrypt its password
        /// </summary>
        public User RegisterUser(User user)
        {
            // Encrypt user password
            user.Password = EncryptionUtils.Encrypt(user.Password);

            return dal.SetUser(user);
        }

        /// <summary>
        /// Method to get User object by email
        /// </summary>
        public User GetUserByEmail(string email)
        {
            return dal.GetUserByEmail(email);
        }

        /// <summary>
        /// Method to get User object by Id
        /// </summary>
        public User GetUserById(int userId)
        {
            return dal.GetUserById(userId);
        }
    }
}
